<template>
  <view class="container">
    <!-- 列表部分 -->
    <scroll-view 
      class="list-container" 
      scroll-y="true"
    >
      <!-- 循环渲染列表项 -->
      <view 
        class="list-item" 
        v-for="(item, index) in list" 
        :key="index"
      >
        <view class="list-item-title">原材料名称：{{ item.goodsName }}</view>
        <view class="list-item-description">
          原始数量：{{ item.quantity }}
        </view>
        <view class="list-item-adjustment">
          统计后数量：
          <input type="text" v-model="item.inventoryAdjustment" @input="validateNumber($event, item, 'inventoryAdjustment')" placeholder="输入统计后数量" />
        </view>
        <view class="list-item-remark">
          备注：
          <input type="text" v-model="item.remark" placeholder="输入备注" />
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="loading" class="loading">加载中...</view>
      <view v-if="finished" class="finished">没有更多数据了</view>

      <!-- 盘库按钮 -->
      <button @click="performInventory">盘库</button>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [],          // 列表数据
      loading: false,    // 是否正在加载
      finished: false,   // 是否加载完成
    };
  },
  methods: {
    // 获取数据
    async fetchData() {
      if (this.loading) return;
      let token = uni.getStorageSync('token');
      this.loading = true;
      const url = this.$C.api_url + 'api/minInventory/getInventoryList';
      uni.request({
        url,
        method: 'GET',
        header:{
          'satoken':token
        },
        success: (res) => {
          const { data } = res.data;
          if (data && data.length > 0) {
            this.list = data.map(item => ({
              ...item,
              inventoryAdjustment: '', // 初始化统计后数量为空字符串
              remark: '' // 初始化备注为空字符串
            }));
          } else {
            uni.showToast({
              title: '暂无权限',
              icon: 'none'
            });
            this.finished = true; 
          }
        },
        fail: (err) => {
          console.error('请求失败', err);
        },
        complete: () => {
          this.loading = false;
        },
      });
    },

    // 验证输入是否为数字
    validateNumber(event, item, field) {
      const value = event.target.value;
      if (value === '' || /^-?\d*(\.\d+)?$/.test(value)) {
        // 允许空字符串，整数和小数
        item[field] = value;
      } else {
        // 清空非法输入
        item[field] = item[field].substring(0, item[field].length - 1);
      }
    },

    // 盘库操作
    performInventory() {
      this.validateAllNumbers();
    },

    // 验证所有统计后数量是否为数字
    validateAllNumbers() {
      let allValid = true;
      for (const item of this.list) {
        if (item.inventoryAdjustment !== '' && !/^-?\d*(\.\d+)?$/.test(item.inventoryAdjustment)) {
          uni.showToast({
            title: '所有统计后数量必须为数字',
            icon: 'none'
          });
          allValid = false;
          break;
        }
      }
      if (allValid) {
        this.submitData(this.list);
      }
    },

    // 提交数据到后端
    submitData(data) {
		console.log(data)
      const url = this.$C.api_url + 'api/minInventory/checkInventory';
      uni.request({
        url,
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'satoken': uni.getStorageSync('token')
        },
        data: JSON.stringify(data),
        success: (res) => {
			console.log(res)
          if (res.data.code == 200) {
            uni.showToast({
              title: '数据提交成功',
              icon: 'success'
            });
			this.fetchData(); 
          } else {
            uni.showToast({
              title: res.data.message || '数据提交失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('数据提交失败', err);
          uni.showToast({
            title: '请求失败，请检查网络',
            icon: 'none'
          });
        }
      });
    }
  },
  onLoad() {
    this.fetchData(); 
  },
  onShow() {
    this.fetchData(); // 页面显示时刷新数据
  },
};
</script>

<style>
.container {
  padding: 20px;
  background-color: #f4f7fb; 
}

.list-container {
  margin-top: 10px;
  min-height: 100vh;
  padding-bottom: 20px;
}

.list-item {
  padding: 20px;
  margin-bottom: 15px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease; 
}

.list-item:hover {
  transform: translateY(-5px); 
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); 
}

.list-item-title {
  font-size: 15px;
  font-weight: bold; /* 加粗字体 */
  color: #333;
  margin-bottom: 5px;
}

.list-item-description, .list-item-adjustment, .list-item-remark {
  font-size: 14px;
  color: #160e1f;
  line-height: 1.6;
  margin-bottom: 5px;
}

.list-item-adjustment input, .list-item-remark input {
  margin-left: 10px;
  width: calc(100% - 120px); /* 根据需要调整输入框的宽度 */
  box-sizing: border-box; /* 确保padding不影响宽度 */
}

.list-item-adjustment, .list-item-remark {
  display: flex;
  align-items: center;
}

.loading, .finished {
  text-align: center;
  color: #888;
  margin-top: 20px;
}

.loading {
  font-size: 16px;
}

.finished {
  font-size: 16px;
  color: #888;
  font-style: italic;
}

button {
  display: block;
  margin: 20px auto;
  padding: 10px 20px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0051cc;
}
</style>